/*
 * @Author       : 吴豪
 * @Date         : 2021-12-4 15:56:22
 * @FilePath     : \book-manage-front\src\pages\bookManage\booksComponents\DamageBook.tsx
 * @Description  : 图书报损模态框
 */

import { damageConfirm } from '@/services/books';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProForm, { ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { message, Modal } from 'antd';
import React, { useRef, useState } from 'react';

type LayoutType = Parameters<typeof ProForm>[0]['layout'];

/**
 * 将父级传来的数据解构，并执行报损操作
 * @param props
 * @returns
 */
const DamageBook = (props: {
  isModalVisible?: any;
  isShowModal?: any;
  actionRef?: any;
  bookAid?: any;
}) => {
  const { isModalVisible } = props;
  const { isShowModal } = props;
  const { actionRef } = props;
  const { bookAid } = props;
  const [formLayoutType] = useState<LayoutType>('horizontal');

  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 16 },
  };

  const formRef = useRef<
    ProFormInstance<{
      aid: number;
      damageQuantity: number;
      remarks: string;
    }>
  >();

  /**
   * 进行图书报损，修改图书数量
   */
  const handleOk = async () => {
    const data = await formRef.current?.validateFields();
    const param = {
      aid: bookAid,
      damageQuantity: data?.damageQuantity || -1,
      remarks: data?.remarks || '',
    };
    const response = await damageConfirm(param);
    if (response) {
      message.success('报损成功！');
      isShowModal(false);
      actionRef.current.reload();
    } else {
      message.error('报损失败！');
    }
  };

  return (
    <Modal
      destroyOnClose
      title="确认损坏"
      width="649px"
      visible={isModalVisible}
      onOk={handleOk}
      onCancel={() => isShowModal()}
    >
      <ProForm
        formRef={formRef}
        submitter={{
          submitButtonProps: {
            style: {
              display: 'none',
            },
          },
          resetButtonProps: {
            style: {
              display: 'none',
            },
          },
        }}
        {...layout}
        layout={formLayoutType}
        params={{}}
      >
        <ProFormText
          name="damageQuantity"
          label="损坏数量"
          placeholder="请输入"
          rules={[
            { required: true },
            { pattern: new RegExp(/^[0-9]\d*$/g), message: '请输入正整数' },
          ]}
        />
        <ProFormTextArea
          fieldProps={{ showCount: true, maxLength: 100 }}
          name="remarks"
          label="备注"
          placeholder="请输入"
        />
      </ProForm>
    </Modal>
  );
};

export default DamageBook;
